package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mysql.cj.util.TimeUtil;
import io.minio.credentials.Jwt;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    //获取验证码实现类
    @Override
    public void sendCode(String phone) {
        //储存验证码的
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //检查指定的手机号对应的验证码是否存到redis中
        boolean hasKey = redisTemplate.hasKey(key);

        if (hasKey){
            //获取该手机号验证码中的剩余过期时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
//            过期时间
            Integer appLoginCodeTtlSec = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //重新发送间隔
            Integer appLoginCodeResendTimeSec = RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;

            //判断是否发送的过于频繁
            if (appLoginCodeTtlSec - expire < appLoginCodeResendTimeSec){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //生成验证码6位数字
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0 ; i<6 ; i++){
            sb.append(random.nextInt(10));
        }
        String string = sb.toString();
        System.out.println("验证码" + string);
        //存储到redis中
        redisTemplate.opsForValue().set(key,string,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }


    //登录的实现
    @Override
    public String login(LoginVo loginVo) {
        //接收手机号和验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);

        //判断验证码是否正确
        if (code == null || !code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //正确就登录或者注册
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        //数据去数据库查找
        if (userInfo == null){
            //注册
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            //佚名 + 手机后四位
            userInfo.setNickname("佚名" + loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //判断用户是否可用
        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //可用
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }
    //获取用户信息实现
    @Override
    public UserInfoVo info(String accessToken) {
        //解析
        Integer userId = (Integer) JwtUtil.parseToken(accessToken).get("userId");
        //查询
        UserInfo userInfoServiceById = userInfoService.getById(userId);
        //封装
        UserInfoVo userInfoVo = new UserInfoVo(userInfoServiceById.getNickname(), userInfoServiceById.getAvatarUrl());
        return userInfoVo;
    }
}
